package com.jie.client.service.ui.view;

import com.jie.client.core.ClientApplication;
import com.jie.client.service.entity.model.Group;
import com.jie.client.service.entity.model.User;
import com.jie.client.service.ui.model.ChatRecordNode;
import com.jie.client.service.ui.view.item.ChatRecordItem;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 聊天记录视图
 * @author XieZhiJie
 * @date 2022/04/28 17:27
 */
public class ChatRecordView {

    private final Logger logger = LoggerFactory.getLogger(ChatRecordView.class);

    /**
     * 0为私聊, 1为群聊
     */
    private final int type;

    /**
     * type为0时不为null
     */
    private final User otherUser;

    /**
     * type为1时不为null
     */
    private final Group group;

    /**
     * 放记录的列表
     */
    private final TableView<ChatRecordItem> chatRecordsTable = new TableView<>();

    public ChatRecordView(User otherUser) {
        this.type = 0;
        this.otherUser = otherUser;
        this.group = null;
    }

    public ChatRecordView(Group group) {
        this.type = 1;
        this.otherUser = null;
        this.group = group;
    }

    public void createChatRecordView() {
        if (this.otherUser == null && this.group == null) {
            return;
        } else if (this.type == 0 && this.otherUser != null) {
            if (ClientApplication.VIEW_MAP.get("singleChatRecords" + this.otherUser.getUserId()) != null) {
                return;
            }
        } else if (this.type == 1 && this.group != null) {
            if (ClientApplication.VIEW_MAP.get("groupChatRecords" + this.group.getGroupId()) != null) {
                return;
            }
        }
        Stage chatRecordStage = new Stage();

        // ======================================聊天记录面板===================================

        VBox crBox = new VBox();

        // 不可编辑里面的信息
        this.chatRecordsTable.setEditable(false);

        // 设置Table的列名(第一个是TableView的泛型类型,第二个是单元格中内容类型)
        TableColumn<ChatRecordItem, String> senderColumn = new TableColumn<>("发送者");
        TableColumn<ChatRecordItem, String> timeColumn = new TableColumn<>("消息时间");
        TableColumn<ChatRecordItem, String> recordColumn = new TableColumn<>("消息内容");

        // 设置time列的宽
        timeColumn.setMinWidth(210);

        // 为列创建数据属性
        senderColumn.setCellValueFactory(
                new PropertyValueFactory<>("sender")
        );
        timeColumn.setCellValueFactory(
                new PropertyValueFactory<>("time")
        );
        recordColumn.setCellValueFactory(
                new PropertyValueFactory<>("record")
        );

        // 确定列名
        this.chatRecordsTable.getColumns().add(senderColumn);
        this.chatRecordsTable.getColumns().add(timeColumn);
        this.chatRecordsTable.getColumns().add(recordColumn);

        // 添加chatRecordsTable进去viewMap
        ChatRecordNode chatRecordNode = new ChatRecordNode(this.chatRecordsTable);
        if (this.type == 0 && this.otherUser != null) {
            // 与otherUser的私聊窗口
            ClientApplication.VIEW_MAP.put("singleChatRecords" + this.otherUser.getUserId(), chatRecordNode);
        } else if (this.type == 1 && this.group != null) {
            // 与这个群的记录窗口
            ClientApplication.VIEW_MAP.put("groupChatRecords" + this.group.getGroupId(), chatRecordNode);
        }

        // 设置单元格最大宽度
        recordColumn.setMaxWidth(150);

        // 单元格被双击以后弹出消息
        this.chatRecordsTable.setRowFactory(param -> {
            TableRow<ChatRecordItem> row = new TableRow<>();
            row.setOnMouseClicked(this::onRecordAction);
            return row;
        });

        // 添加组件
        crBox.getChildren().add(this.chatRecordsTable);

        // 设置crBox边距
        crBox.setPadding(new Insets(10, 5, 10, 5));

        // 如果这个窗口关掉了, 就把这个列表从viewMap中去掉
        if (this.type == 0 && this.otherUser != null) {
            chatRecordStage.setOnCloseRequest(event -> ClientApplication.VIEW_MAP.remove("singleChatRecords" + this.otherUser.getUserId()));
        } else if (this.type == 1 && this.group != null) {
            chatRecordStage.setOnCloseRequest(event -> ClientApplication.VIEW_MAP.remove("groupChatRecords" + this.group.getGroupId()));
        }

        // 布置场景
        Scene scene = new Scene(crBox, 378, 450);
        chatRecordStage.setScene(scene);
        chatRecordStage.setTitle("双击查看某条聊天记录");
        chatRecordStage.show();
    }

    /**
     * 点击聊天记录
     * @param event 点击事件
     */
    private void onRecordAction(MouseEvent event) {
        if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
            // 哪一项被选中
            int index = this.chatRecordsTable.getSelectionModel().getSelectedIndex();
            ChatRecordItem chatRecordItem = null;
            try {
                chatRecordItem = this.chatRecordsTable.getItems().get(index);
            } catch (ArrayIndexOutOfBoundsException e) {
                this.logger.info("点到空白内容了...");
            }
            if (chatRecordItem == null) {
                return;
            }
            // 再生成一个窗口出来
            Stage aMsgStage = new Stage();
            TextArea aMsgText = new TextArea();
            aMsgText.setEditable(false);
            aMsgText.appendText(chatRecordItem.getSender()
                    + " "
                    + chatRecordItem.getTime()
                    + "\n"
                    + chatRecordItem.getRecord()
            );

            Scene scene = new Scene(aMsgText, 300, 100);
            aMsgStage.setScene(scene);
            aMsgStage.setTitle("一条记录");
            aMsgStage.show();
        }
    }

}
